<template>
  <view class="date-picker-container">
    <!-- 触发按钮 -->
    <view class="trigger-btn" @click="showPicker">
      <text>{{ displayText }}</text>
      <image src="/static/image/paipan/time.svg" class="icon-time" />
    </view>

    <!-- 日期选择器弹窗 -->
    <view class="picker-modal" v-if="visible" @click="hidePicker">
      <view class="picker-content" @click.stop>
        <!-- 头部 -->
        <view class="picker-header">
          <text class="cancel-btn" @click="hidePicker">取消</text>
          <text class="title">选择日期</text>
          <text class="confirm-btn" @click="confirmSelect">确定</text>
        </view>

        <!-- 日历类型切换 -->
        <view class="calendar-type">
          <view
            class="type-btn"
            :class="{ active: calendarType === 'solar' }"
            @click="switchCalendarType('solar')"
          >
            阳历
          </view>
          <view
            class="type-btn"
            :class="{ active: calendarType === 'lunar' }"
            @click="switchCalendarType('lunar')"
          >
            阴历
          </view>
        </view>

        <!-- 日期时间选择器 -->
        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="onPickerChange"
          :indicator-style="indicatorStyle"
        >
          <!-- 年 -->
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(year, index) in yearRange"
              :key="index"
            >
              {{ year }}年
            </view>
          </picker-view-column>

          <!-- 月 -->
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(month, index) in monthRange"
              :key="index"
            >
              {{ calendarType === "lunar" ? month : month + "月" }}
            </view>
          </picker-view-column>

          <!-- 日 -->
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(day, index) in dayRange"
              :key="index"
            >
              {{ calendarType === "lunar" ? day : day + "日" }}
            </view>
          </picker-view-column>

          <!-- 时 -->
          <picker-view-column v-if="showTime">
            <view
              class="picker-item"
              v-for="(hour, index) in hourRange"
              :key="index"
            >
              {{ hour }}时
            </view>
          </picker-view-column>

          <!-- 分 -->
          <picker-view-column v-if="showTime">
            <view
              class="picker-item"
              v-for="(minute, index) in minuteRange"
              :key="index"
            >
              {{ minute }}分
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
  </view>
</template>

<script>
// 引入农历转换库
import calendar from "js-calendar-converter";

export default {
  name: "DatePicker",
  props: {
    // 控制显示隐藏
    show: {
      type: Boolean,
      default: false,
    },
    // 默认值
    value: {
      type: [Date, String],
      default: null,
    },
    // 是否显示时间
    showTime: {
      type: Boolean,
      default: false,
    },
    // 最小年份
    minYear: {
      type: Number,
      default: 1900,
    },
    // 最大年份
    maxYear: {
      type: Number,
      default: 2100,
    },
  },

  data() {
    return {
      visible: this.show,
      calendarType: "solar", // solar: 公历, lunar: 农历
      pickerValue: [0, 0, 0, 0, 0], // [年, 月, 日, 时, 分]
      selectedDate: null,
      indicatorStyle: "height: 50px;",
      // 农历日期中文数字映射
      lunarDayMap: [
        "",
        "初一",
        "初二",
        "初三",
        "初四",
        "初五",
        "初六",
        "初七",
        "初八",
        "初九",
        "初十",
        "十一",
        "十二",
        "十三",
        "十四",
        "十五",
        "十六",
        "十七",
        "十八",
        "十九",
        "二十",
        "廿一",
        "廿二",
        "廿三",
        "廿四",
        "廿五",
        "廿六",
        "廿七",
        "廿八",
        "廿九",
        "三十",
      ],
      // 农历月份中文映射
      lunarMonthMap: [
        "",
        "正月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "腊月",
      ],
      isTime: false,
    };
  },

  computed: {
    // 年份范围
    yearRange() {
      const years = [];
      for (let i = this.minYear; i <= this.maxYear; i++) {
        years.push(i);
      }
      return years;
    },

    // 月份范围
    monthRange() {
      if (this.calendarType === "lunar") {
        return this.getLunarMonths();
      }
      const months = [];
      for (let i = 1; i <= 12; i++) {
        months.push(i);
      }
      return months;
    },

    // 日期范围
    dayRange() {
      if (this.calendarType === "lunar") {
        return this.getLunarDays();
      }
      return this.getSolarDays();
    },

    // 小时范围
    hourRange() {
      const hours = [];
      for (let i = 0; i < 24; i++) {
        hours.push(i.toString().padStart(2, "0"));
      }
      return hours;
    },

    // 分钟范围
    minuteRange() {
      const minutes = [];
      for (let i = 0; i < 60; i++) {
        minutes.push(i.toString().padStart(2, "0"));
      }
      return minutes;
    },

    // 显示文本 - 根据日历类型显示对应格式
    displayText() {
      if (!this.selectedDate || !this.isTime) {
        return "请选择日期";
      }

      const date = new Date(this.selectedDate);

      if (this.calendarType === "lunar") {
        // 显示农历日期
        const lunarDate = this.solarToLunar(
          date.getFullYear(),
          date.getMonth() + 1,
          date.getDate()
        );

        if (lunarDate) {
          const yearText = `${lunarDate.lYear}年`;
          const monthText = lunarDate.isLeap
            ? `闰${this.lunarMonthMap[lunarDate.lMonth]}`
            : this.lunarMonthMap[lunarDate.lMonth];
          const dayText = this.lunarDayMap[lunarDate.lDay];

          let text = `${yearText}${monthText}${dayText}`;

          if (this.showTime) {
            const hour = date.getHours().toString().padStart(2, "0");
            const minute = date.getMinutes().toString().padStart(2, "0");
            text += ` ${hour}:${minute}`;
          }

          return text;
        } else {
          // 农历转换失败，显示公历日期
          return this.getSolarDisplayText(date);
        }
      } else {
        // 显示公历日期
        return this.getSolarDisplayText(date);
      }
    },
  },

  watch: {
    show(newVal) {
      this.visible = newVal;
    },

    visible(newVal) {
      this.$emit("update:show", newVal);
    },
  },

  mounted() {
    this.initDefaultValue();
  },

  methods: {
    // 显示选择器
    showPicker() {
      this.visible = true;
    },

    // 隐藏选择器
    hidePicker() {
      this.visible = false;
    },

    // 切换日历类型
    switchCalendarType(type) {
      this.calendarType = type;
      if (type === "lunar") {
        this.switchToLunar();
      } else {
        this.initPickerValue();
      }
    },

    // 初始化默认值 - 默认使用当前时间
    initDefaultValue() {
      const now = new Date();
      this.selectedDate = this.value ? new Date(this.value) : now;
      this.initPickerValue();
    },

    // 初始化picker值
    initPickerValue() {
      const date = this.selectedDate || new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minute = date.getMinutes();

      this.pickerValue = [
        this.yearRange.indexOf(year),
        month - 1,
        day - 1,
        hour,
        minute,
      ];
    },

    // 获取公历天数
    getSolarDays() {
      const year = this.yearRange[this.pickerValue[0]];
      const month = this.monthRange[this.pickerValue[1]];
      const daysInMonth = new Date(year, month, 0).getDate();

      const days = [];
      for (let i = 1; i <= daysInMonth; i++) {
        days.push(i);
      }
      return days;
    },

    // 获取农历月份 - 修改为显示中文月份和闰月
    getLunarMonths() {
      const year = this.yearRange[this.pickerValue[0]];
      const months = [];

      try {
        // 基本月份
        for (let i = 1; i <= 12; i++) {
          months.push({
            month: i,
            display: this.lunarMonthMap[i],
            isLeap: false,
          });
        }

        // 使用正确的API获取闰月
        const leapMonth = calendar.leapMonth(year);
        console.log(leapMonth, "leapMonthleapMonth");

        if (leapMonth > 0) {
          // 在闰月位置插入闰月
          const leapMonthObj = {
            month: leapMonth,
            display: `闰${this.lunarMonthMap[leapMonth]}`,
            isLeap: true,
          };
          months.splice(leapMonth, 0, leapMonthObj);
        }
      } catch (error) {
        console.error("获取农历月份失败:", error);
        // 默认返回12个月
        for (let i = 1; i <= 12; i++) {
          months.push({
            month: i,
            display: this.lunarMonthMap[i],
            isLeap: false,
          });
        }
      }

      return months.map((m) => m.display);
    },

    // 获取农历天数 - 修改为显示中文日期
    getLunarDays() {
      const year = this.yearRange[this.pickerValue[0]];
      const monthValue = this.monthRange[this.pickerValue[1]];
      const days = [];

      try {
        let month = 1;
        let isLeapMonth = false;

        // 重新获取月份信息用于计算
        const monthsInfo = this.getLunarMonthsInfo();
        const monthInfo = monthsInfo[this.pickerValue[1]];
        if (monthInfo) {
          month = monthInfo.month;
          isLeapMonth = monthInfo.isLeap;
        }

        // 获取该月的天数
        let daysInMonth = 30; // 默认30天

        // 通过尝试转换来确定本月天数
        for (let day = 28; day <= 30; day++) {
          try {
            const result = calendar.lunar2solar(year, month, day, isLeapMonth);
            if (result && result.cYear) {
              daysInMonth = day;
            } else {
              break;
            }
          } catch (e) {
            break;
          }
        }

        for (let i = 1; i <= daysInMonth; i++) {
          days.push(this.lunarDayMap[i]);
        }
      } catch (error) {
        console.error("获取农历天数失败:", error);
        // 默认返回30天
        for (let i = 1; i <= 30; i++) {
          days.push(this.lunarDayMap[i]);
        }
      }

      return days;
    },

    // 获取农历月份信息（用于内部计算）
    getLunarMonthsInfo() {
      const year = this.yearRange[this.pickerValue[0]];
      const months = [];

      try {
        // 基本月份
        for (let i = 1; i <= 12; i++) {
          months.push({
            month: i,
            display: this.lunarMonthMap[i],
            isLeap: false,
          });
        }

        // 使用正确的API获取闰月
        const leapMonth = calendar.leapMonth(year);
        if (leapMonth > 0) {
          const leapMonthObj = {
            month: leapMonth,
            display: `闰${this.lunarMonthMap[leapMonth]}`,
            isLeap: true,
          };
          months.splice(leapMonth, 0, leapMonthObj);
        }
      } catch (error) {
        console.error("获取农历月份信息失败:", error);
        for (let i = 1; i <= 12; i++) {
          months.push({
            month: i,
            display: this.lunarMonthMap[i],
            isLeap: false,
          });
        }
      }

      return months;
    },

    // picker变化事件
    onPickerChange(e) {
      this.pickerValue = e.detail.value;
    },

    // 确认选择
    confirmSelect() {
      this.isTime = true;
      const year = this.yearRange[this.pickerValue[0]];
      const hour = this.showTime
        ? parseInt(this.hourRange[this.pickerValue[3]])
        : 0;
      const minute = this.showTime
        ? parseInt(this.minuteRange[this.pickerValue[4]])
        : 0;

      let resultDate;

      if (this.calendarType === "lunar") {
        // 获取农历月份和日期信息
        const monthsInfo = this.getLunarMonthsInfo();
        const monthInfo = monthsInfo[this.pickerValue[1]];
        const dayText = this.dayRange[this.pickerValue[2]];
        const day = this.lunarDayMap.indexOf(dayText);

        if (monthInfo && day > 0) {
          // 农历转公历
          const solarDate = this.lunarToSolar(
            year,
            monthInfo.month,
            day,
            monthInfo.isLeap
          );
          if (solarDate) {
            resultDate = new Date(
              solarDate.cYear,
              solarDate.cMonth - 1,
              solarDate.cDay,
              hour,
              minute
            );
          } else {
            // 转换失败，使用当前日期
            resultDate = new Date();
            console.error("农历转公历失败");
          }
        } else {
          resultDate = new Date();
        }
      } else {
        // 公历
        const month = this.monthRange[this.pickerValue[1]];
        const day = this.dayRange[this.pickerValue[2]];
        resultDate = new Date(year, month - 1, day, hour, minute);
      }

      this.selectedDate = resultDate;
      this.hidePicker();

      // 触发change事件
      this.$emit("change", {
        date: resultDate,
        calendarType: this.calendarType,
        formattedDate: this.formatDate(resultDate), // 返回格式化的日期
        originalValue: this.getOriginalValue(year, hour, minute),
      });
    },

    // 格式化日期为YYYY-MM-DD格式
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");

      let formatted = `${year}-${month}-${day}`;

      if (this.showTime) {
        const hour = date.getHours().toString().padStart(2, "0");
        const minute = date.getMinutes().toString().padStart(2, "0");
        formatted += ` ${hour}:${minute}:00`;
      }

      return formatted;
    },

    // 获取原始选择值
    getOriginalValue(year, hour, minute) {
      if (this.calendarType === "lunar") {
        const monthsInfo = this.getLunarMonthsInfo();
        const monthInfo = monthsInfo[this.pickerValue[1]];
        const dayText = this.dayRange[this.pickerValue[2]];
        const day = this.lunarDayMap.indexOf(dayText);

        return {
          year,
          month: monthInfo ? monthInfo.month : 1,
          day,
          hour,
          minute,
          isLeapMonth: monthInfo ? monthInfo.isLeap : false,
          monthDisplay: monthInfo ? monthInfo.display : "",
          dayDisplay: dayText,
        };
      } else {
        const month = this.monthRange[this.pickerValue[1]];
        const day = this.dayRange[this.pickerValue[2]];
        return {
          year,
          month,
          day,
          hour,
          minute,
          isLeapMonth: false,
        };
      }
    },

    // 农历转公历（使用js-calendar-converter库）
    lunarToSolar(lunarYear, lunarMonth, lunarDay, isLeapMonth = false) {
      try {
        const result = calendar.lunar2solar(
          lunarYear,
          lunarMonth,
          lunarDay,
          isLeapMonth
        );
        if (result && result.cYear) {
          return result;
        }
        return null;
      } catch (error) {
        console.error("农历转公历失败:", error);
        return null;
      }
    },

    // 公历转农历（辅助方法）
    solarToLunar(solarYear, solarMonth, solarDay) {
      try {
        const result = calendar.solar2lunar(solarYear, solarMonth, solarDay);
        if (result && result.lYear) {
          return result;
        }
        return null;
      } catch (error) {
        console.error("公历转农历失败:", error);
        return null;
      }
    },

    // 切换到农历时，将当前公历日期转换为农历 - 修复版本
    switchToLunar() {
      if (this.selectedDate) {
        const date = new Date(this.selectedDate);
        const lunarDate = this.solarToLunar(
          date.getFullYear(),
          date.getMonth() + 1,
          date.getDate()
        );

        if (lunarDate) {
          // 更新picker值为农历日期
          const yearIndex = this.yearRange.indexOf(lunarDate.lYear);
          if (yearIndex >= 0) {
            this.pickerValue[0] = yearIndex;
          }

          // 使用 $nextTick 确保 monthRange 已经重新计算
          this.$nextTick(() => {
            // 重新获取月份信息来找到正确的索引
            const monthsInfo = this.getLunarMonthsInfo();
            let monthIndex = -1;
            for (let i = 0; i < monthsInfo.length; i++) {
              if (
                monthsInfo[i].month === lunarDate.lMonth &&
                monthsInfo[i].isLeap === lunarDate.isLeap
              ) {
                monthIndex = i;
                break;
              }
            }

            if (monthIndex >= 0) {
              this.pickerValue[1] = monthIndex;
            }

            // 再次使用 $nextTick 确保 dayRange 也已经重新计算
            this.$nextTick(() => {
              // 设置农历日期
              if (lunarDate.lDay > 0 && lunarDate.lDay <= 30) {
                this.pickerValue[2] = lunarDate.lDay - 1;
              }

              // 强制更新pickerValue以触发视图更新
              this.pickerValue = [...this.pickerValue];
            });
          });
        }
      }
    },

    // 获取公历显示文本的辅助方法
    getSolarDisplayText(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");

      let text = `${year}-${month}-${day}`;

      if (this.showTime) {
        const hour = date.getHours().toString().padStart(2, "0");
        const minute = date.getMinutes().toString().padStart(2, "0");
        text += ` ${hour}:${minute}`;
      }

      return text;
    },
  },
};
</script>

<style lang="scss" scoped>
.date-picker-container {
  position: relative;
}

.trigger-btn {
  display: flex;
  align-items: center;
  justify-content: flex-end;

  background: #fdfcf2;
  min-height: 80rpx;
  box-sizing: border-box;

  &:active {
    background: #f5f5f5;
  }
}

.picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.picker-content {
  width: 100%;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  border-bottom: 2rpx solid #f0f0f0;

  .cancel-btn,
  .confirm-btn {
    font-size: 32rpx;
    color: #007aff;
  }

  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }
}

.calendar-type {
  display: flex;
  margin: 40rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  padding: 8rpx;

  .type-btn {
    flex: 1;
    text-align: center;
    padding: 16rpx 32rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;

    &.active {
      background: #007aff;
      color: #fff;
    }
  }
}

.picker-view {
  height: 480rpx;
  margin: 0 40rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  font-size: 32rpx;
  color: #333;
}

.lunar-info {
  text-align: center;
  padding: 32rpx 40rpx;
  color: #666;
  font-size: 28rpx;
  background: #f8f8f8;
  margin: 0 40rpx 40rpx;
  border-radius: 16rpx;
}
.icon-time {
  margin-left: 20rpx;
  width: 46rpx;
  height: 46rpx;
}
</style>
